package en.edu.zxj.rabbit.extensions.demo.config;

import en.edu.zxj.rabbit.extensions.demo.constant.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA.
 * Description：配置死信队列
 *
 * @author: zxj
 * @date: 2024-09-21
 * @time: 16:19:46
 */
// @Configuration
public class DLXConfig {
    // 死信交换机
    @Bean("dlxExchange")
    public Exchange dlxExchange() {
        return ExchangeBuilder.directExchange(Constants.DLX_EXCHANGE_NAME).durable(true).build();
    }

    // 死信队列
    @Bean("dlxQueue")
    public Queue dlxQueue() {
        return QueueBuilder.durable(Constants.DLX_QUEUE_NAME).build();
    }

    // 绑定
    @Bean("dlxBind")
    public Binding dlxBind(@Qualifier("dlxQueue") Queue queue, @Qualifier("dlxExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Constants.DLX_ROUTING_KEY).noargs();
    }

    // 正常交换机
    @Bean("normalExchange")
    public Exchange normalExchange() {
        return ExchangeBuilder
                .directExchange(Constants.NORMAL_EXCHANGE_NAME)
                .durable(true)
                .build();
    }

    // 正常队列
    @Bean("normalQueue")
    public Queue normalQueue() {
        return QueueBuilder
                .durable(Constants.NORMAL_QUEUE_NAME)
                .deadLetterExchange(Constants.DLX_EXCHANGE_NAME).deadLetterRoutingKey(Constants.DLX_ROUTING_KEY) // 正常队列绑定死信交换机
                .ttl(10 * 1000).maxLength(10L) // 制造死信产⽣的条件: 10s后消息变成死信, 队列最多存10条消息
                .build();
    }

    // 绑定
    @Bean("normalBind")
    public Binding normalBind(@Qualifier("normalQueue") Queue queue, @Qualifier("normalExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Constants.NORMAL_ROUTING_KEY).noargs();
    }
}
